package org.comet.auxiliary.client.liaobei.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.comet.auxiliary.client.swing.versions.v1.SettingFrame;
import org.comet.auxiliary.common.util.HttpUtils;
import org.comet.auxiliary.common.util.JsonUtils;
import org.comet.auxiliary.common.util.MapBean;
import org.comet.auxiliary.common.util.crypto.MD5Util;

import javax.swing.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wq
 * @date 2019/9/30
 * @description template
 * 遗留代码, 无实际用处
 */
public class RequestUtil {

    private static ConcurrentHashMap<String, String> balanceUuidMap = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<String, String> balanceTokenMap = new ConcurrentHashMap<>();

    public static String post(String url, String uid, String uuid, MapBean data) throws IOException {
        return post(url, uid, uuid, data, 5000);
    }

    public static String post(String url, String uid, String uuid, MapBean data, int socketTimeout) throws IOException {
        Map<String, String> params = new HashMap<>(16);
        params.put("data", JsonUtils.getJsonString(data));
        params.put("ver", "1.4.2.0");
        params.put("cpt", System.currentTimeMillis() + "");
        params.put("uuid", uuid);
        params.put("uid", uid);

        Map<String, String> heads = new HashMap<>(8);
        heads.put("User-Agent", "Lim/2.0.5 (com.chaoqu.lailiaobei; build:39; iOS 13.1.2) Alamofire/0.0.1");

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3100)
                .setSocketTimeout(socketTimeout)
                .setCookieSpec("mySpec")
                .build();

        String result;
        try {
            String url0 = "https://api.liaobe.cn/" + url;
            if (url.contains("http")) {
                url0 = url;
            }
            result = HttpUtils.httpClientPost(url0, heads, params, requestConfig);
        } catch (Exception err) {
            JOptionPane.showMessageDialog(null,"通讯异常");
            throw err;
        }
        return result;
    }

    public static String getQRCode(String uuid) throws IOException {
        MapBean data = new MapBean();
        data.put("dv", 3);
        String qrCodeRes = post("authlg/gqrc", "-1", uuid, data);
        Map<String, Object> qrRes = JsonUtils.getMap(qrCodeRes);
        qrRes = (Map<String, Object>) qrRes.get("data");
        String img = qrRes.get("img").toString();
        return "http://r.liaobepic.cn/" + img;
    }

    public static Map<String, Object> checkQRCode(String uuid) throws IOException {
        MapBean data = new MapBean();
        data.put("os", "ThunderOS 2.0");
        data.put("di", "Chrome Browser");
        data.put("dv", 3);
        // tp=1: 可查询扫描后未确认时头像信息   tp=2: 查询tk等信息
        data.put("tp", 2);

        String checkResStr = post("authlg/lwqrc", "-1", uuid, data);
        Map<String, Object> checkRes = JsonUtils.getMap(checkResStr);
        boolean checkIsTrue = "0".equals(checkRes.get("r").toString());
        if (checkIsTrue) {
            return (Map<String, Object>) checkRes.get("data");
        } else {
            return null;
        }
    }

    public static Map<String, Object> refreshToken(String uuid, String uid, String rtk) throws IOException {
        MapBean data = new MapBean();
        data.put("rtk", rtk);

        String result = post("auth/rt", uid, uuid, data);
        Map<String, Object> res = JsonUtils.getMap(result);
        System.err.println("refreshToken:: " + res);
        boolean checkIsTrue = "0".equals(res.get("r").toString());
        if (checkIsTrue) {
            return (Map<String, Object>) res.get("data");
        } else {
            return null;
        }
    }

    public static Map<String, Object> checkToken(String uuid, String uid, String tk) throws IOException {
        MapBean data = new MapBean();
        data.put("tk", tk);

        String result = post("auth/ct", uid, uuid, data);
        Map<String, Object> res = JsonUtils.getMap(result);
        System.err.println("checkToken:: " + res);
        boolean checkIsTrue = "0".equals(res.get("r").toString());
        if (checkIsTrue) {
            return (Map<String, Object>) res.get("data");
        } else {
            return null;
        }
    }

    public static Map<String, Object> queryFriendList(String uuid, String uid, String tk) throws IOException {
        MapBean data = new MapBean();
        data.put("tk", tk);
        String checkResStr = post("cht/gcl", uid, uuid, data, 7000);
        Map<String, Object> checkRes = JsonUtils.getMap(checkResStr);
        return (Map<String, Object>) checkRes.get("data");
    }

    public static String sendPacket(String packetText, Integer packetAmt, String toId, String pwd, String tk, String uid, String uuid) throws IOException {
        MapBean data = new MapBean();
        data.put("tuid", toId);
        double amt = packetAmt / 100d;
        data.put("amt", amt);
        data.put("pwd", MD5Util.getMD5(pwd));
        data.put("msg", packetText);
        data.put("tp", 1);
        data.put("tk", tk);
        return post("csh/sptusrhb", uid, uuid, data);
    }

    public static String sendRelationPacket(String packetText, Integer packetAmt, Integer count, String rid, String pwd, String tk, String uid, String uuid) throws IOException {
        double amt = packetAmt / 100d;
        MapBean data = new MapBean();
        data.put("rid", rid);
        data.put("msg", packetText);
        data.put("pwd", MD5Util.getMD5(pwd));
        data.put("amt", amt);
        data.put("tp", 1);
        data.put("tk", tk);
        data.put("cnt", count);
        return post("csh/srhb", uid, uuid, data);
    }

    public static String takePacket(String uid, String uuid, String tk, String tno, String fuid) throws IOException {
        MapBean data = new MapBean();
        data.put("tno", tno);
        data.put("fuid", fuid);
        data.put("tp", 1);
        data.put("tk", tk);
        return post("csh/rhb", uid, uuid, data);
    }

    public static String queryPacket(String uid, String uuid, String tk, String tno, String fuid) throws IOException {
        MapBean data = new MapBean();
        data.put("tno", tno);
        data.put("fuid", fuid);
        data.put("tp", 1);
        data.put("tk", tk);
        return post("csh/hb", uid, uuid, data);
    }

    public static String queryUserByMid(String uid, String uuid, String tk, String mid) throws IOException {
        MapBean data = new MapBean();
        data.put("mid", mid);
        data.put("tk", tk);
        return post("s/sn", uid, uuid, data);
    }

    public static String addFriend(String uid, String uuid, String tk, String liaobeiId, String fuid, String rmk) throws IOException {
        MapBean data = new MapBean();
        String idh = getIdh(uid, uuid, tk, liaobeiId, fuid);
        data.put("idh", idh);
        data.put("rmk", rmk);
        data.put("at", 1);
        data.put("tk", tk);
        return post("ct/auf", uid, uuid, data);
    }

    public static String getIdh(String uid, String uuid, String tk, String liaobeiId, String fuid) throws IOException {
        MapBean data = new MapBean();
        data.put("tuid", fuid);
        data.put("tlid", liaobeiId);
        data.put("tk", tk);
        String res = post("usr/guih", uid, uuid, data);
        Map<String, Object> result = JsonUtils.getMap(res);
        if ("0".equals(result.get("r").toString())) {
            result = (Map<String, Object>) result.get("data");
            return result.get("idh").toString();
        }
        return null;
    }

    public static String getTokenInfo(String uid, String uuid, String tk) throws IOException {
        String key = uid + "-" + uuid;
        if (balanceTokenMap.containsKey(key)) {
            return balanceTokenMap.get(key);
        }
        String uuidByLD = getUuidByLD(uid, uuid, tk);
        if (uuidByLD != null) {
            System.out.println("===find uuid:: " + uuidByLD);
            uuid = uuidByLD;
        }

        Map<String, Object> params = new HashMap<>(16);
        params.put("app_user_id", uid);
        params.put("app_id", "LB");
        params.put("device_uuid", uuid);

        Map<String, String> heads = new HashMap<>(8);
        heads.put("User-Agent", "Lim/2.0.5 (com.chaoqu.lailiaobei; build:39; iOS 13.1.2) Alamofire/0.0.1");

        StringEntity entity = new StringEntity(JsonUtils.getJsonString(params), ContentType.create("application/json", "UTF-8"));

        String result = HttpUtils.httpClientPost("https://api.liaopay.cn/user_center/user/getTokenInfo.do",
                heads, entity);
        Map<String, Object> res = JsonUtils.getMap(result);
        if ("1".equals(res.get("result").toString())) {
            res = (Map<String, Object>) res.get("data");
            String opToken = res.get("op_token").toString();
            balanceTokenMap.put(key, opToken);
            balanceTokenMap.put(opToken, key);
            return opToken;
        }
        return null;
    }

    public static String queryBalance(String opToken) throws IOException {
        Map<String, String> heads = new HashMap<>(8);
        heads.put("User-Agent", "Lim/2.0.5 (com.chaoqu.lailiaobei; build:39; iOS 13.1.2) Alamofire/0.0.1");

        Map<String, String> params0 = new HashMap<>(4);
        params0.put("op_token", opToken);

        StringEntity entity0 = new StringEntity(JsonUtils.getJsonString(params0), ContentType.create("application/json", "UTF-8"));
        String result = HttpUtils.httpClientPost("https://api.liaopay.cn/user_center/account/accountInfo.do",
                heads, entity0);

        Map<String, Object> balanceRes = JsonUtils.getMap(result);
        String resultFlag0 = balanceRes.get("result").toString();
        boolean ok0 = "1".equals(resultFlag0);
        if (ok0) {
            balanceRes = (Map<String, Object>) balanceRes.get("data");
            return balanceRes.get("amount").toString();
        }
        String realKey = balanceTokenMap.remove(opToken);
        balanceTokenMap.remove(realKey);
        return null;
    }

    private static String getUuidByLD(String uid, String uuid, String tk) throws IOException {
        String key = uid + "-" + uuid;
        if (balanceUuidMap.containsKey(key)) {
            return balanceUuidMap.get(key);
        }
        String listDevice = listDevice(uid, uuid, tk);
        Map<String, Object> res = JsonUtils.getMap(listDevice);
        if ("0".equals(res.get("r").toString())) {
            res = (Map<String, Object>) res.get("data");
            List<Map<String, Object>> dl = (List<Map<String, Object>>) res.get("dl");
            for (Map<String, Object> device : dl) {
                String dv = device.get("dv").toString();
                if ("2".equals(dv) || "1".equals(dv)) {
                    String uuid0 = device.get("uuid").toString();
                    balanceUuidMap.put(key, uuid0);
                    return uuid0;
                }
            }
        }
        return null;
    }

    public static String listDevice(String uid, String uuid, String tk) throws IOException {
        MapBean data = new MapBean();
        data.put("tk", tk);
        return post("usr/ld", uid, uuid, data);
    }

    public static String lod(String uid, String uuid, String tk) throws IOException {
        return lod(uid, uuid, tk, null);
    }

    public static String lod(String uid, String uuid, String tk, String outUuid) throws IOException {
        MapBean data = new MapBean();
        data.put("tk", tk);
        if (outUuid != null) {
            data.put("duuid", outUuid);
        }
        return post("usr/lod", uid, uuid, data);
    }

}
